/**
 * @(#)MonitorBaseService.java 2017年2月15日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.monitor.service;


import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsbd.boss.common.ExportExcel;
import org.jsbd.boss.common.monitor.MonitorContentTemplate;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.service.IMonitorConfigService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 数据监控基类
 * @author <a href="mailto:zhouchao@xingbook.com" >周超</a>
 * @version 1.0.0
 */
public abstract class MonitorBaseService {
	public static final Logger LOGGER = LoggerFactory.getLogger(MonitorBaseService.class);
	
	protected DecimalFormat RATE_FORMAT = new DecimalFormat("#0.0000");
	
	protected static final int INTERVAL_TIME=30;
	
	protected static final int ONE_HOUR_TIME=60*60*1000;
	protected static final int THIRTY_MINUTE_TIME=30*60*1000;
	
	protected static String DAILY_REPORT_PATH = PropertiesUtil.getValue("dailyReportPath", "/tmp/report/");

	@Autowired
	private RedisClient<String,Date> redisClient;
	@Autowired
	private IMonitorConfigService monitorConfigService;
	
	/**
	 * 
	 * 获取监控内容列表数据与邮件附件
	 * @author <a href="mailto:zhouchao@xingbook.com" >周超</a>
	 * @param apkList
	 * @param apkConfigMap
	 * @return
	 */
	public abstract Map<String,String> getMonitorContent(List<ChannelApkConfig> apkList,Map<String,ChannelApkConfig> apkConfigMap,Map<String,Object> conditionMap); 
	
	
	public Map<String,Object> getConditionMap(){
		
		long currentTime=System.currentTimeMillis();
		Date startTime=(Date)redisClient.get(CacheKey.MONITOR_STARTTIME_KEY+getKey());
		//如果开始时间小于半个小时，则不执行
		if(startTime!=null&&startTime.getTime()>currentTime-THIRTY_MINUTE_TIME){
			return null;
		}
		
		//如果开始时间距离现在大于了1个小时，则重新赋值为之前半小时
		if(startTime==null||(startTime.getTime()>currentTime-ONE_HOUR_TIME)){
			startTime=getPreMinitusTime(new Date());
		}
		
		Map<String,Object> conditionMap=new HashMap<String,Object>();
		conditionMap.put("currentDate", DateUtil.getCurrentDateStr());
		conditionMap.put("startTime", startTime);
	    conditionMap.put("endTime", new Date());
		
	    redisClient.put(CacheKey.MONITOR_STARTTIME_KEY+getKey(),startTime);
	    
	    return conditionMap;
	}
	
	public String getKey(){
		return this.getClass().getSimpleName();
	}
	
	public Date getPreMinitusTime(Date time){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.MINUTE,-INTERVAL_TIME);
		return calendar.getTime();
	}
	
	public Date getNextMinitusTime(Date time){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.MINUTE,INTERVAL_TIME);
		return calendar.getTime();
	}
	
	/**
	 * 
	 * 根据数据生成excel
	 * @author <a href="mailto:zhouchao@xingbook.com" >周超</a>
	 * @param headerInfoArr
	 * @param attachName
	 * @param resultList
	 * @return
	 */
	protected String productEmailAttachment(String[][] headerInfoArr,String attachName,List<?>... resultList){
		ExportExcel excel=new ExportExcel();
		int len=headerInfoArr.length;
    	String[] headerArr=new String[len];
    	for(int i=0;i<len;i++){
    		headerArr[i]=headerInfoArr[i][0];
    	}
    	
    	String attachment = DAILY_REPORT_PATH +attachName+"_" + DateUtil.getCurrentDateTime() + ".xls";
    	int sheetNum=0;
    	for(List<?> dataList:resultList){
        	try {
    			excel.exportMultiSheetExcel2003(sheetNum, "模拟器任务监控"+sheetNum, headerArr, dataList, attachment, "yyyyMMdd");
    			sheetNum++;
    		} catch (FileNotFoundException e) {
    			attachment=null;
    		}
    	}
    	return attachment;
	}
	
	/**
	 * 
	 * 生产邮件内容
	 * @author <a href="mailto:zhouchao@xingbook.com" >周超</a>
	 * @param resultList
	 * @param headerInfoArr
	 * @return
	 */
	public String productEmailContent(List<?> resultList,String[][] headerInfoArr){
	    return MonitorContentTemplate.getHtmlTableInfo(resultList, headerInfoArr);
	}
	
	public Map<String,String> getMonitorResultMap(List<?> resultList,String[][] headerInfoArr,String sheetName){
		Map<String,String> resultMap=new HashMap<String,String>();
		
		if(resultList==null||resultList.isEmpty()){
			return resultMap;
		}
		StringBuffer buffer=new StringBuffer();
		
        buffer.append(productEmailContent(resultList,headerInfoArr));
		String attachFile=productEmailAttachment(headerInfoArr,sheetName,resultList);
		resultMap.put("content", buffer.toString());
		resultMap.put("attachFile", attachFile);
		
		if("MOBILE_RATE".equals(sheetName)){
			resultMap.put("sheetName", "手机获取数监控");
		}else if("SIMULATOR_NUM_MONITOR".equals(sheetName)){
			resultMap.put("sheetName", "模拟器数量监控");
		}else if("SIMULATOR_ACTION_MONITOR".equals(sheetName)){
			resultMap.put("sheetName", "模拟器行为监控");
		}else{
			resultMap.put("sheetName",sheetName);
		}
		
		return resultMap;
	}
	
	protected Map<String,String> productExceptionMap(Exception e,String monitorName){
		Map<String,String> exceptionMap=new HashMap<String,String>();
		exceptionMap.put("sheetName", monitorName);
		exceptionMap.put("content", e.getMessage());
		return exceptionMap;
	}
	
	public Map<String,String> getMonitorConfig(){
		return monitorConfigService.getAllMonitorConfigMap();
	}
	
	
	
}
